<template>
    <div class="question-form-container">
      <el-form :model="questionData"
               ref="questionForm"
               label-width="120px"
               :rules="questionRules"
               status-icon>
        <el-form-item prop="title" label="问答标签">
          <el-input
            v-model="questionData.title"
            clearable
            show-word-limit
            style="width: 70%"
            maxlength="50"
          ></el-input>
        </el-form-item>

        <el-form-item style="width: 73%" label="问答内容">
          <tinymce :height="300" v-model="questionData.content"/>
        </el-form-item>

        <el-form-item prop="tag" label="问答标签">
          <el-select
            style="width: 70%"
            v-model="questionData.tag"
            multiple
            size="medium"
            filterable
            :multiple-limit="3"
            placeholder="请选择标题，最多可选择三个，可进行搜索">
            <el-option
              v-for="item in tagList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            class="question-btn"
            type="primary"
            @click="editQuestion">确认修改</el-button>
        </el-form-item>
      </el-form>

    </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import {validNormal} from '@/utils/validate'
  import { getQuestionById,updateQuestionById } from '@/api/question'
  import { getAllTag } from '@/api/tag'

  export default {
    data(){

      //检验标题
      const validateTitle = (rule, value, callback) => {
        if (value.length < 5 || value.length > 50 || !value || !validNormal(value) ){
          callback(new  Error("请输入正确的问题标题，长度要求为5-50，且不能输入特殊字符"))
        }
        else callback()
      }

      //检验标签
      const validateTag = (rule, value, callback) => {
        if (value.length < 1){
          callback(new  Error("请至少选择一个标签"))
        }
        callback()
      }

      return {
        tagList:[],
        questionData: {
          contentId: '',
          questionId: '',
          title: '',
          tag: '',
          content: '',
        },
        questionRules:{
          title:[{validator: validateTitle,trigger: 'blur'}],
          tag:[{validator: validateTag,trigger: ['blur','change'] ,type:'number'}],
        }
      }
    },

    methods: {
      init(){
        if (this.$route.params && this.$route.params.id) {
          const id = this.$route.params.id
          this.fetchDataById(id)
          this.initTagList()

        } else {
          // 使用对象拓展运算符，拷贝对象，而不是引用，
          // 否则新增一条记录后，defaultForm就变成了之前新增的teacher的值
          this.questionData = { ...defaultForm }
        }
      },

      fetchDataById(id){
        getQuestionById(id).then(result => {
          if (result.code === 20000){
            this.questionData = result.data.item
            this.questionData.tag = this.questionData.tag.split(',')
          }
        })
      },

      initTagList(){
        getAllTag().then(result => {
          if (result.code === 20000){
            this.tagList = result.data.items
          }
        })
      },

      editQuestion(){
        this.questionData.tag = this.questionData.tag.join(',')
        this.$refs.questionForm.validate((valid) => {
          if (valid) {
            //检验通过
            updateQuestionById(this.questionData.questionId,this.$qs.stringify(this.questionData)).then(result => {
              if (result.code === 20000){
                this.$router.push({ path: '/manage/question' })
                this.$message({
                  type: 'success',
                  message: '修改成功！'
                })
              }
            })
          }
        })
      }
    },

    created() {
      this.init()
    },

    watch:{
      $route(to, from) {
        this.init()
      }
    },

    components:{
      Tinymce
    },
  }
</script>

<style scoped>
  .question-form-container{
    margin-top: 20px;
    margin-left: -25px;
  }
  .tinymce-container {
    position: relative;
    line-height: normal;
  }
</style>
